package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @description:
 * @author: pandeng_zhu
 * @time: 2023/2/13 13:58
 */

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Override
    public void sendSms(String mobile, String templateCode, String smsCode, Map<String, Object> param) {


        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(SmsProperties.KEY_ID)
                .accessKeySecret(SmsProperties.KEY_SECRET)
                .build());

        //配置客户端
        AsyncClient client = AsyncClient.builder()
                .region(SmsProperties.REGION_Id) // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
        //创建远程连接的参数
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(SmsProperties.SIGN_NAME)
                .templateCode(SmsProperties.TEMPLATE_CODE)
                .phoneNumbers(mobile)
                .templateParam("{\"code\":\"" + smsCode + "\"}")
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = null;
        try {
            resp = response.get();
            //获取响应结果
            String data = new Gson().toJson(resp);//转为json格式

            JSONObject jsonObject = JSONObject.parseObject(data);
            //根据key取value的值
            String code = jsonObject.getJSONObject("body").getString("code");
            String message = jsonObject.getJSONObject("body").getString("message");
            log.info("code：" + code + "，message：" + message);

            //业务失败的处理
            Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);

        } catch (InterruptedException e) {
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        } catch (ExecutionException e) {
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        }
        System.out.println(new Gson().toJson(resp));
        client.close();

    }


/*
        //创建远程连接客户端对象
        DefaultProfile profile = DefaultProfile.getProfile(
                SmsProperties.REGION_Id,
                SmsProperties.KEY_ID,
                SmsProperties.KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        //创建远程连接的请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", SmsProperties.REGION_Id);
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", SmsProperties.SIGN_NAME);
        request.putQueryParameter("TemplateCode", templateCode);

        Gson gson = new Gson();
        String jsonParam = gson.toJson(param);
        request.putQueryParameter("TemplateParam", jsonParam);
        try {
            //使用客户端对象携带请求参数向远程阿里云服务器发起远程调用，并得到响应结果
            CommonResponse response = client.getCommonResponse(request);
            System.out.println("response.getData()：" + response.getData());
            //response.getData()：{"Message":"请检查模板内容与模板参数是否匹配","RequestId":"3C3B5FB8-AC33-580B-83F9-D3A575A1C40F","Code":"isv.SMS_TEMPLATE_ILLEGAL"}

            //通信失败的处理
            boolean success = response.getHttpResponse().isSuccess();
            Assert.isTrue(success, ResponseEnum.ALIYUN_RESPONSE_FAIL);

            //获取响应结果
            String data = response.getData();
            System.out.println("data::::::::::" + data);
            //data::::::::::{"Message":"请检查模板内容与模板参数是否匹配","RequestId":"3C3B5FB8-AC33-580B-83F9-D3A575A1C40F","Code":"isv.SMS_TEMPLATE_ILLEGAL"}

            HashMap<String, String> resultMap = gson.fromJson(data, HashMap.class);
            String code = resultMap.get("Code");
            String message = resultMap.get("Message");
            //log.info("code：" + code + "，message：" + message);

            //业务失败的处理
            Assert.notEquals("isv.SMS_TEMPLATE_ILLEGAL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);

        } catch (ServerException e) {
            log.error("阿里云短信发送sdk调用失败:" + e.getErrCode() + ", " + e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        } catch (ClientException e) {
            log.error("阿里云短信发送sdk调用失败:" + e.getErrCode() + ", " + e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        }*/
}


